#include <func.h>
int main(int argc, char *argv[])
{
    // ./5_azhen_epoll_reconnect 192.168.38.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET; // AF_INET ipv4
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    int flag = 1; // 给SO_REUSEADDR属性的参数分配内存
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(flag));
    // 赋值用具体类型 传参时强转成公共类型
    ret = bind(sockfd,(struct sockaddr *)&addr, sizeof(addr));
    // 服务端 bind 只能绑定服务端地址
    ERROR_CHECK(ret,-1,"bind");
    listen(sockfd,10);

    int epfd = epoll_create(1);
    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = sockfd;
    epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&event);
    char buf[4096];
    int netfd = -1;
    struct epoll_event readyset[10];
    while(1){
        int readynum = epoll_wait(epfd,readyset,10,-1);
        for(int i = 0; i < readynum; ++i){
            if(readyset[i].data.fd == sockfd){
                netfd = accept(sockfd,NULL,NULL);

                event.events = EPOLLIN;
                event.data.fd = STDIN_FILENO;
                epoll_ctl(epfd,EPOLL_CTL_ADD,STDIN_FILENO,&event);
                event.events = EPOLLIN;
                event.data.fd = netfd;
                epoll_ctl(epfd,EPOLL_CTL_ADD,netfd,&event);
                epoll_ctl(epfd,EPOLL_CTL_DEL,sockfd,NULL);
            }
            else if(readyset[i].data.fd == STDIN_FILENO){
                bzero(buf,sizeof(buf));
                ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
                if(sret == 0){
                    send(netfd,"nishigehaoren",13,0);
                    close(netfd);
                    epoll_ctl(epfd,EPOLL_CTL_DEL,netfd,NULL);
                    epoll_ctl(epfd,EPOLL_CTL_DEL,STDIN_FILENO,NULL);
                    event.events = EPOLLIN;
                    event.data.fd = sockfd;
                    epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&event);
                    netfd = -1;
                    break;
                }
                send(netfd,buf,strlen(buf),0);
            }
            else if(readyset[i].data.fd == netfd){
                bzero(buf,sizeof(buf));
                ssize_t sret = recv(netfd,buf,sizeof(buf),0);
                if(sret == 0){
                    printf("Hehe\n");
                    close(netfd);
                    epoll_ctl(epfd,EPOLL_CTL_DEL,netfd,NULL);
                    epoll_ctl(epfd,EPOLL_CTL_DEL,STDIN_FILENO,NULL);
                    event.events = EPOLLIN;
                    event.data.fd = sockfd;
                    epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&event);
                    netfd = -1;
                    break;
                }
                printf("buf = %s\n", buf);
            }
        }
    }
    return 0;
}

